package com.tre.jdevtemplateboot.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author JDev
 */
public class FileDownloadUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileDownloadUtils.class);

    private FileDownloadUtils() {
    }

    public static void fileDownload(String filePath, String fileName, HttpServletResponse response) {
        downLoad(filePath + File.separator + fileName, response);
    }

    public static void fileDownload(String filePath, String fileName) {

        downLoad(filePath + File.separator + fileName, HttpUtils.getHttpServletResponse());
    }

    public static void fileDownload(String fileName) {
        downLoad(fileName, HttpUtils.getHttpServletResponse());
    }

    private static void downLoad(String filePath, HttpServletResponse response) {

        File file = new File(filePath);
        BufferedOutputStream os = null;
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buffer = new byte[inputStream.available()];
            response.reset();
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(file.getName().replaceAll(" +", "")
                            .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" + file.length());
            os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
                os.flush();
            }
        } catch (Exception e) {
            logger.error("======File download exception======", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }

}
